package exercises.newcoder.solution;

/**
 * <a href="https://www.nowcoder.com/practice/d8b6b4358f774294a89de2a6ac4d9337?tpId=117&&tqId=37735">
 *     NC33 合并两个排序的链表</a>
 * <pre>{@code
 * public class ListNode {
 *     int val;
 *     ListNode next = null;
 *
 *     ListNode(int val) {
 *         this.val = val;
 *     }
 * }}</pre>
 * @author or2
 * @Description
 * @create 2021年08月31日 时间: 10:30
 */
public class ListNodeMerge {
    public ListNode Merge(ListNode list1,ListNode list2) {
        ListNode p1 = list1;
        ListNode p2 = list2;

        ListNode head = new ListNode(0);
        ListNode headP = head;
        while (p1 != null && p2 != null) {
            ListNode listNode;
            if (p1.val < p2.val) {
                listNode = new ListNode(p1.val);
                p1 = p1.next;
            } else {
                listNode = new ListNode(p2.val);
                p2 = p2.next;
            }
            headP.next = listNode;
            headP = listNode;
        }

        while (p1 != null) {
            headP.next = new ListNode(p1.val);
            headP = headP.next;
            p1 = p1.next;
        }
        while (p2 != null) {
            headP.next = new ListNode(p2.val);
            headP = headP.next;
            p2 = p2.next;
        }

        return head.next;
    }

    private static class ListNode {
        int val;
        ListNode next = null;

        ListNode(int val) {
            this.val = val;
        }
    }

}